
<html>
<head>
<title>Results:</title>
<link rel=stylesheet href="style.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>
<?php
require_once('db_connect.php');

$area_min = pg_escape_string($_GET['area_min']);
$area_max = pg_escape_string($_GET['area_max']); 
$room_min = pg_escape_string($_GET['room_min']); 
$room_max = pg_escape_string($_GET['room_max']); 
$price_min = pg_escape_string($_GET['price_min']); 
$price_max = pg_escape_string($_GET['price_max']); 
$rent_min = pg_escape_string($_GET['rent_min']); 
$rent_max = pg_escape_string($_GET['rent_max']); 

$result = pg_query('SELECT DISTINCT lan FROM bostader');
$num_rows = pg_num_rows($result);

$sql_stmt = "";
$is_first = TRUE;
for($i = 0; $i < $num_rows; $i++){
	if(isset($_GET["lan$i"])){
		if($is_first){
			$is_first = FALSE;
			$sql_stmt .= " AND(lan = '".pg_escape_string($_GET["lan$i"])."'";
		}else{
			$sql_stmt .= " OR lan = '".pg_escape_string($_GET["lan$i"])."'";
		}
	}
}
if(!$is_first){
	$sql_stmt .= ')';
}

$result = pg_query('SELECT DISTINCT objekttyp FROM bostader');
$num_rows = pg_num_rows($result);

$is_first = TRUE;
for($i = 0; $i < $num_rows; $i++){
        if(isset($_GET["type$i"])){
                if($is_first){
                        $is_first = FALSE;
                        $sql_stmt .= " AND(objekttyp = '".pg_escape_string($_GET["type$i"])."'";
                }else{
                        $sql_stmt .= " OR objekttyp = '".pg_escape_string($_GET["type$i"])."'";
                }
        }
}
if(!$is_first){
        $sql_stmt .= ')';
}


//echo $sql_stmt;
if($area_max != 'max')
	$sql_stmt .= " AND area <= $area_max";
if($room_max != 'max')
        $sql_stmt .= " AND rum <= $room_max";
if($price_max != 'max')
        $sql_stmt .= " AND pris <= $price_max";
if($rent_max != 'max')
        $sql_stmt .= " AND avgift <= $rent_max";

echo '<table>';
echo '<tr><th>Province</th><th>Type</th><th>Address</th><th>Living 
area</th><th>Rooms</th><th>Price</th><th>Fee/Rent</th></tr>';
$result = pg_query("SELECT * FROM bostader WHERE area >= '$area_min' AND rum >= '$room_min' AND pris >= '$price_min' 
AND avgift >= '$rent_min' ".$sql_stmt);
while($row = pg_fetch_assoc($result)){
	echo '<tr>';
        echo '<td>'.$row['lan'].'</td>';
        echo '<td>'.$row['objekttyp'].'</td>';
        echo '<td>'.$row['adress'].'</td>';
        echo '<td>'.$row['area'].'</td>';
	echo '<td>'.$row['rum'].'</td>';
	echo '<td>'.$row['pris'].'</td>';
	echo '<td>'.$row['avgift'].'</td>';
	echo '</tr>';
}
?>
</table>
</body>
</html>
